package com.lk.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.lk.mapper.PostMapper;
import com.lk.model.domain.Post;
import com.lk.service.PostService;
import com.lk.utils.AliOssUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.*;

@Service
@Transactional(rollbackFor = Exception.class)
public class PostServiceImpl extends ServiceImpl<PostMapper,Post>
                                                            implements PostService{

    @Resource
    private PostMapper postMapper;

    @Resource
    private AliOssUtil aliOssUtil;

    @Override
    public int addPost(Post post) {
        int i = postMapper.insert(post);
        return i;
    }

    @Override
    public List<Post> selectAll() {
        return postMapper.selectAll();
    }

    /**
     * 创建帖子时上传图片，返回路径
     * @param file
     * @param request
     * @return
     */
    @Override
    public String saveFile(MultipartFile file, HttpServletRequest request) {
        //上传头像
        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新文件名
            String objectName = UUID.randomUUID().toString();
            objectName=objectName+extension;
            //文件请求路径
            String Path = aliOssUtil.upload(file.getBytes(), objectName);

            System.out.println("post图片路径："+Path);

            return Path;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 点赞帖子
     *
     * @param id
     * @param userId
     * @return
     */
    @Override
    public int addLike(Long id, Long userId) {
        // 参数校验
        if (id == null || userId == null) {
            throw new IllegalArgumentException("postId 和 userId 不能为空");
        }

        // 根据帖子id获取帖子
        Post post = postMapper.getById(id);
        if (post == null) {
            throw new IllegalArgumentException("帖子不存在");
        }

        // 获取 followsIds
        String followsIds = post.getFollowsIds();
        List<Integer> followsIdList;
        Gson gson = new Gson();

        // 如果 followsIds 为空或 null，则初始化一个空列表
        if (followsIds == null || followsIds.isEmpty()) {
            followsIdList = new ArrayList<>();
        } else {
            // 否则，尝试解析 JSON 字符串为 List<Integer>
            Type listType = new TypeToken<List<Integer>>(){}.getType();
            try {
                followsIdList = gson.fromJson(followsIds, listType);
            } catch (JsonSyntaxException e) {
                // 处理 JSON 解析异常，例如记录日志或抛出更具体的异常
                throw new IllegalArgumentException("无效的 followsIds JSON 格式", e);
            }
        }

        //先遍历数组是否存在该用户id,则对该用户不添加不修改
        if(followsIdList.contains(userId.intValue())) {
            return followsIdList.size();
        }

        // 添加 userId 到 followsIdList
        followsIdList.add(userId.intValue());

        // 将 List<Integer> 转为 JSON 字符串
        followsIds = gson.toJson(followsIdList);

        // 更新数据库
        int updateResult = postMapper.addLikeToDataBase(id, followsIds, followsIdList.size());

        // 返回操作后的followsIds的值
        return followsIdList.size();
    }


    /**
     * 取消点赞
     *
     * @param id
     * @param userId
     * @return
     */
    @Override
    public int lessLike(Long id, Long userId) {
        // 参数校验
        if (id == null || userId == null) {
            throw new IllegalArgumentException("postId 和 userId 不能为空");
        }

        // 根据帖子id获取帖子
        Post post = postMapper.getById(id);
        if (post == null) {
            throw new IllegalArgumentException("帖子不存在");
        }

        // 获取 followsIds
        String followsIds = post.getFollowsIds();
        List<Integer> followsIdList;
        Gson gson = new Gson();

        // 如果 followsIds 为空或 null，则初始化一个空列表
        if (followsIds == null || followsIds.isEmpty()) {
            followsIdList = new ArrayList<>();
        } else {
            // 否则，尝试解析 JSON 字符串为 List<Integer>
            Type listType = new TypeToken<List<Integer>>(){}.getType();
            try {
                followsIdList = gson.fromJson(followsIds, listType);
            } catch (JsonSyntaxException e) {
                // 处理 JSON 解析异常，例如记录日志或抛出更具体的异常
                throw new IllegalArgumentException("无效的 followsIds JSON 格式", e);
            }
        }

        //先遍历数组是否不存在该用户id,则对该用户不删除不修改
        if (!followsIdList.contains(userId.intValue())) {
            return followsIdList.size();
        }

        // 添加 userId 从followsIdList删除
        followsIdList.remove(Integer.valueOf(userId.intValue()));

        // 将 List<Integer> 转为 JSON 字符串
        followsIds = gson.toJson(followsIdList);

        // 更新数据库
        int updateResult = postMapper.addLikeToDataBase(id, followsIds, followsIdList.size());

        // 返回操作结果
        return followsIdList.size();
    }

    @Override
    public String getCommentDetail(Long postId) {
        return postMapper.getCommentDetail(postId);
    }

    @Override
    public int addComment(Long postId, String json) {
        return postMapper.addComment(postId, json);
    }

    @Override
    public void updateCommentNum(Long postId, int size) {
        postMapper.updateCommentNum(postId, size);
    }

    @Override
    public int deletePost(Long postId) {
        return postMapper.deleteById(postId);
    }
}
